package cn.easier.activity.console.controller;

import cn.easier.activity.console.configration.ActivityConsoleConfiguration;
import cn.easier.activity.console.entity.ActivityConsoleUser;
import cn.easier.activity.console.service.ActivityInfoService;
import cn.easier.activity.console.service.ActivityPrizeService;
import cn.easier.activity.console.utils.FileUtil;
import cn.easier.activity.web.entity.ActivityInfo;
import cn.easier.activity.web.entity.ActivityPrize;
import cn.easier.activity.web.entity.PrizeType;
import cn.easier.club.base.dto.ResultInfo;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 活动奖品Controller
 */
@Controller
@RequestMapping("/activity/activityInfoId/{activityInfoId}/prize")
public class ActivityPrizeController extends BaseController{

    Logger logger = LoggerFactory.getLogger(ActivityPrizeController.class);
    @Autowired
    ActivityInfoService activityInfoService;

    @Autowired
    ActivityPrizeService activityPrizeService;

    @Autowired
    ActivityConsoleConfiguration activityConsoleConfiguration;


    /**
     * 查找指定活动奖品列表
     */
    @GetMapping
    @ResponseBody
    public ResultInfo findActivityPrizes(@PathVariable Integer activityInfoId) {
        //todo 如果当前用户不存在，返回异常
        ResultInfo resultInfo = null;
        String user = getPrincipal().getUsername();
        String authoritiesStr = getPrincipal().getAuthoritiesStr();
        //查看关联的活动，如果此活动属于当前用户，根据活动编号获取指定规则。
        ActivityInfo activityInfo = getActivityInfo(authoritiesStr, user, activityInfoId);
        if (activityInfo == null) {
            logger.error("获取活动奖品列表失败，当前用户不拥有指定活动对象。user: =>{},activityInfoId:=>{}", user, activityInfoId);
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "获取活动奖品列表失败", null);

        }
        List<ActivityPrize> activityPrizes = activityPrizeService.findByActivityInfoId(activityInfoId);
        resultInfo = new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "SUCCESS", activityPrizes);
        logger.info("获取活动奖品列表成功：=>{}", activityPrizes);
        return resultInfo;
    }

    /**
     * 查找指定活动券码奖品列表
     *
     * @return
     */
    @GetMapping("coupon-code-list")
    @ResponseBody
    public ResultInfo findCouponCodeList(@PathVariable Integer activityInfoId) {
        //todo 如果当前用户不存在，返回异常
        ResultInfo resultInfo = null;
        String user = getPrincipal().getUsername();
        String authoritiesStr = getPrincipal().getAuthoritiesStr();
        ActivityInfo activityInfo = getActivityInfo(authoritiesStr, user, activityInfoId);
        //查看关联的活动，如果此活动属于当前用户，根据活动编号获取指定规则。
        if (activityInfo == null) {
            logger.error("获取活动奖品列表失败，当前用户不拥有指定活动对象。user: =>{},activityInfoId:=>{}", user, activityInfoId);
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "获取活动奖品列表失败", null);

        }
        List<ActivityPrize> activityPrizes = activityPrizeService.findByActivityInfoId(activityInfoId);
        List<ActivityPrize> couponCodeList = new ArrayList<ActivityPrize>();
        for (ActivityPrize activityPrize : activityPrizes) {
            if (PrizeType.ELECTRONIC_COUPON.equals(activityPrize.getPrizeType())) {
                couponCodeList.add(activityPrize);
            }
        }
        resultInfo = new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "SUCCESS", couponCodeList);
        logger.info("获取活动奖品列表成功：=>{}", couponCodeList);
        return resultInfo;
    }

    /**
     * 查找指定活动指定奖品
     *
     * @return
     */
    @GetMapping("/id/{id}")
    @ResponseBody
    public ResultInfo findOne(@PathVariable Integer activityInfoId, @PathVariable Integer id) {
        //todo 如果当前用户不存在，返回异常
        ResultInfo resultInfo = null;
        String user = getPrincipal().getUsername();
        String authoritiesStr = getPrincipal().getAuthoritiesStr();
        ActivityInfo activityInfo = getActivityInfo(authoritiesStr, user, activityInfoId);
        //查看关联的活动，如果此活动属于当前用户，根据活动编号获取指定规则。
        if (activityInfo == null) {
            logger.error("获取活动奖品失败，当前用户不拥有指定活动对象。user: =>{},activityInfoId:=>{}", user, activityInfoId);
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "获取活动奖品失败", null);

        }
        //关联活动Id,防止假传奖品Id
        ActivityPrize activityPrize = activityPrizeService.findOne(id, activityInfoId);
        resultInfo = new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "SUCCESS", activityPrize);
        logger.info("获取活动奖品成功：=>{}", activityPrize);
        return resultInfo;
    }

    /**
     * 创建或更新活动奖品
     * 抓娃娃模式复用了这里 用PC 和WAP 的IMAGE存入的是相对应的 PC 高配  WAP 低配
     *
     * @return
     */
    @PostMapping
    @ResponseBody
    public ResultInfo saveOrUpdate(@PathVariable Integer activityInfoId, ActivityPrize activityPrize, @RequestParam(value = "pcImageFile", required = false)
            MultipartFile pcImageFile, @RequestParam(value = "wapImageFile", required = false)
                                           MultipartFile wapImageFile) {
        ResultInfo resultInfo = null;
        String user = getPrincipal().getUsername();
        String authoritiesStr = getPrincipal().getAuthoritiesStr();
        //判断添加或者更新
        if (null != activityPrize.getId()) {
            activityInfoId = activityPrize.getActivityInfoId();
        } else {
            activityPrize.setActivityInfoId(activityInfoId);
        }
        try {
            //查看关联的活动，如果此活动属于当前用户，根据活动编号获取指定规则。
            ActivityInfo activityInfo = getActivityInfo(authoritiesStr, user, activityInfoId);
            if (activityInfo == null) {
                logger.error("创建或更新活动奖品异常，当前用户不拥有指定活动对象。user: =>{},activityInfoId:=>{}", user, activityInfoId);
                return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "创建活动奖品异常", null);
            }
            //pc和wap图片上传
            if (pcImageFile != null && (!Strings.isNullOrEmpty(pcImageFile.getOriginalFilename()))) {
                String fileName = pcImageFile.getOriginalFilename();
                //验证图片文件格式
                boolean imageFormatFlag = FileUtil.imageFormatVerification(fileName);
                if (!imageFormatFlag) {
                    return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "请选择格式为*.jpg、*.gif、*.bmp、*.png、*.jpeg 的图片", fileName);
                }
                String pcPath = activityConsoleConfiguration.activityPrizePcImagePath;
                activityPrize.setPcImage(uploadFile(pcImageFile, pcPath, "activity_image_pc_"));
            }
            if (wapImageFile != null && (!Strings.isNullOrEmpty(wapImageFile.getOriginalFilename()))) {
                String fileName = wapImageFile.getOriginalFilename();
                //验证图片文件格式
                boolean imageFormatFlag = FileUtil.imageFormatVerification(fileName);
                if (!imageFormatFlag) {
                    return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "请选择格式为*.jpg、*.gif、*.bmp、*.png、*.jpeg 的图片", fileName);
                }
                String wapPath = activityConsoleConfiguration.activityPrizeWapImagePath;
                activityPrize.setWapImage(uploadFile(wapImageFile, wapPath, "activity_image_wap_"));
            }
            ActivityPrize returnActivityPrize = activityPrizeService.saveAndFlush(activityPrize);
            logger.info("创建或更新活动奖品成功：=>{}", returnActivityPrize);
            resultInfo = new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "创建或更新活动奖品成功", returnActivityPrize);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("创建或更新活动奖品失败，activityInfoId：=>{}", activityInfoId);
            resultInfo = new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "创建或更新活动奖品异常", null);
        }
        return resultInfo;
    }

    private String uploadFile(MultipartFile imageFile, String prizePath, String fileNamePrefix) {
        //根路径
        String realPath = activityConsoleConfiguration.realPath;
        //文件路径
        String path = (realPath + prizePath).replace("/", File.separator);
        String imageFileName = FileUtil.doFile(imageFile, path, fileNamePrefix);
        //静态资源映射 + 文件地址 + 上传文件名称
        return prizePath + imageFileName;
    }

    /**
     * 删除指定活动指定奖品
     *
     * @return
     */
    @DeleteMapping("/id/{id}")
    @ResponseBody
    public ResultInfo delete(@PathVariable Integer activityInfoId, @PathVariable Integer id) {
        //todo 如果当前用户不存在，返回异常
        ResultInfo resultInfo = null;
        String user = getPrincipal().getUsername();
        String authoritiesStr = getPrincipal().getAuthoritiesStr();
        try {
            //查看关联的活动，如果此活动属于当前用户，根据活动编号获取指定规则。
            ActivityInfo activityInfo = getActivityInfo(authoritiesStr, user, activityInfoId);
            if (activityInfo == null) {
                logger.error("获取活动奖品失败，当前用户不拥有指定活动对象。user: =>{},activityInfoId:=>{}", user, activityInfoId);
                return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "删除活动奖品失败，用户信息有误", null);

            }
            //关联活动Id,防止假传奖品Id
            Boolean deleteFlag = activityPrizeService.delete(id, activityInfoId);
            resultInfo = new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "SUCCESS", deleteFlag);
            logger.info("删除奖品： id =>{}，flag =>{}", id, deleteFlag ? "SUCCESS" : "No Change");
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("删除奖品异常： id =>{}", id);
            resultInfo = new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "删除活动奖品异常", null);
        }
        return resultInfo;
    }

}
